package com.shop.loan.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderBillByMybatisMapper;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.ProductByMybatisMapper;
import com.shop.loan.model.entity.LoanOrderBillByMybatis;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.ProductByMybatis;
import com.shop.loan.model.vo.UpdateOrderMoneyVo;
import com.shop.loan.util.Util;
import org.springframework.stereotype.Component;
import xyz.erupt.annotation.fun.OperationHandler;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Component
public class UpdateOrderMoneyHandler implements OperationHandler<Object, UpdateOrderMoneyVo> {

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    LoanOrderBillByMybatisMapper loanOrderBillByMybatisMapper;

    @Resource
    ProductByMybatisMapper productByMybatisMapper;

    @Override
    public String exec(List<Object> data, UpdateOrderMoneyVo updateOrderMoneyVo, String[] param) {
        if (updateOrderMoneyVo.getProduct() == null) {
            return "msg.error('产品不能为空!')";
        }
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");


        ProductByMybatis product = productByMybatisMapper.selectByPrimaryKey(updateOrderMoneyVo.getProduct().getId());
        if (product == null) {
            return "msg.error('产品异常!')";
        }

        Integer loanPeriod = product.getLoanPeriod();
        Integer loanPeriodDay = product.getLoanDay() / loanPeriod;
        //利息
        BigDecimal rateMoney = Util.getRateMoney(product.getMoney(), product.getYearRate(), product.getLoanDay());

        LoanOrderByMybatis loanOrderByMybatis = new LoanOrderByMybatis();
        loanOrderByMybatis.setId(id);
        loanOrderByMybatis.setRateMoney(rateMoney);
        loanOrderByMybatis.setMoney(product.getMoney());
        loanOrderByMybatis.setYearRate(product.getYearRate());
        loanOrderByMybatis.setPeriodDay(loanPeriodDay);
        loanOrderByMybatis.setPeriod(product.getLoanPeriod());
        loanOrderByMybatisMapper.updateByPrimaryKeySelective(loanOrderByMybatis);
        loanOrderBillByMybatisMapper.deleteByOrderId(id);

        List<LoanOrderBillByMybatis> periodDateList = Util.getPeriodList(loanOrderByMybatis);
        for (int i = 0; i < periodDateList.size(); i++) {
            LoanOrderBillByMybatis loanOrderBillByMybatis = periodDateList.get(i);
            loanOrderBillByMybatisMapper.insertSelective(loanOrderBillByMybatis);
        }
        return null;
    }
}
